package com.dave.gd.core.base.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.dave.gd.common.log.ILogger;
import com.dave.gd.common.log.LoggerFactory;
import com.dave.gd.common.util.DateUtils;
import com.dave.gd.core.base.entity.impl.AbstractBaseEntity;
import com.dave.gd.core.base.service.IFileService;
import com.dave.gd.core.common.pagehelper.PageInfo;

/**
 * 
 * 
 * @ClassName: FileService
 * @Description: 文件上传/下载Service
 * @author majx
 * @date 2014-8-21 上午11:41:47
 * 
 */
@SuppressWarnings("rawtypes")
@Service("fileService")
public class FileServiceImpl extends AbstractGenericService implements IFileService {
    private static final String  CONF_FILE_PROPERTIES = "conf/file.properties";
    public ILogger               logger               = LoggerFactory.getLogger(this.getClass());
    private static Configuration config               = null;
    static {
        if (config == null) {
            try {
                config = new PropertiesConfiguration(CONF_FILE_PROPERTIES);
            } catch (ConfigurationException e) {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public void saveFile(Map<String, Object> parms) {
        
        if (config != null) {
            String save_path = config.getString("save_path");
            if (StringUtils.isNotBlank(save_path))
                saveFile(save_path, parms);
        }
        saveFile(FileUtils.getUserDirectoryPath(), parms);
    }
    
    /**
     * (非 Javadoc)
     * <p>
     * Title: saveFile
     * </p>
     * <p>
     * Description:
     * </p>
     * 
     * @param parms
     * @return
     */
    
    @Override
    public void saveFile(String uploadPath, Map<String, Object> parms) {
        File[] files = (File[]) parms.get("file");
        String[] realNames = (String[]) parms.get("fileFileName");
        Date date = new Date();
        File saveDirectory = new File(getSavePath(uploadPath, date));
        if (files.length > 0 && !saveDirectory.exists() && !saveDirectory.isDirectory()) {
            saveDirectory.mkdirs();
        }
        for (int i = 0; i < files.length; i++) {
            String extension = FilenameUtils.getExtension(realNames[i]);
            String realName = FilenameUtils.getBaseName(realNames[i]);
            String saveName = realName + extension;
            try {
                FileUtils.copyFile(files[i], new File(saveDirectory, saveName));
            } catch (IOException e) {
                logger.error(e.getMessage());
                continue;
            }
        }
    }
    
    public static String getSavePath() {
        return getSavePath(FileUtils.getUserDirectoryPath());
    }
    
    public static String getSavePath(Date date) {
        return getSavePath(FileUtils.getUserDirectoryPath(), date);
    }
    
    public static String getSavePath(String uploadPath) {
        return getSavePath(uploadPath, new Date());
    }
    
    public static String getSavePath(String uploadPath, Date d) {
        
        StringBuffer sb = new StringBuffer();
        return sb.append(uploadPath).append(File.separator).append(DateUtils.getYear(d))
            .append(File.separator).append(DateUtils.getMonth(d)).append(File.separator)
            .append(DateUtils.getDay(d)).toString();
        
    }
    
    /**
     * (非 Javadoc)
     * <p>
     * Title: readFile
     * </p>
     * <p>
     * Description:
     * </p>
     * 
     * @param fileBean
     * @return
     */
    @Override
    public InputStream readFile(String savePath, String name) {
        savePath = getSavePath(savePath);
        File file = new File(savePath, name);
        FileInputStream openInputStream = null;
        try {
            openInputStream = FileUtils.openInputStream(file);
            
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return openInputStream;
    }
    
    @Override
    public InputStream readFile(String name) {
        if (config != null) {
            String save_path = config.getString("save_path");
            if (StringUtils.isNotBlank(save_path))
                return readFile(save_path, name);
        }
        String save_path = FileUtils.getUserDirectoryPath();
        return readFile(save_path, name);
    }
    
    public static void main(String[] args) throws ConfigurationException {
        
        Configuration config = new PropertiesConfiguration(CONF_FILE_PROPERTIES);
        String save_path = config.getString("save_path");
        System.out.println(save_path);
    }

    @Override
    public AbstractBaseEntity get(Serializable id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List listAll() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List listByMap(Map map) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public PageInfo findPageInfoByMap(Map map, int page, int pageSize) {
        // TODO Auto-generated method stub
        return null;
    }
}
